// 页面: 工作台-审批管理-审批
const $app = getApp()
Page({
  data: {
    Auth: {}, // 权限数据(勿删)
    userInfo: $app.userInfo || {}, // 用户信息
    // ===== 参数 =====
    param: {
      agreeType: '0', // 执行状态 0:待审批/1:审批中/2:已同意/3:已退回
      agreeResult: '同意',
      agreeIdea: null, // 审批意见
      pageNo: 1, // 第几页
      pageSize: 10 // 一页几条数据
    },
    // ========== 数据相关 ==========
    data: [], // 消息数据
    total: 0, // 数据总数
    refreshing: false, // 是否正在刷新中
    loading: false, // 是否正在加载中
    backTop: false, // 滚动条回到顶部(只要改变值就回到顶部)
    // ========== 数据项相关 ==========
    detailData: {}, // 详情数据
    // ===== 列表数据 =====
    listData: {
      agreeType: $app.listData.approve, // 执行状态
      manageType: $app.listData.manageType, // 管理方式
      agreeResult: ['同意', '不同意']
    },
    // ===== 判断 =====
    judgeAuth: {},
    // ===== 弹框参数 =====
    dialogShow: null // 显示隐藏
    // ===== end =====
  },
  model (e) { $app.$common_wx.model(e, this) }, // 双向绑定
  // ========== 生命周期: 页面加载 ==========
  onLoad: function (options) {
    this.setData({ userInfo: $app.userInfo })
    // ========== 获取权限数据(勿删) ==========
    // 获取租赁维修其他审批权限
    $app.$common_base.getAuth('work_approve_apply').then((Auth) => {
      this.setData({ Auth })
      this.judgeAuthEvent() // 判断权限
    })
    // 出租/退租        1/2     rentApprove_manage_submit
    // 维修             3      repairApprove_manage_submit
    // 其他/拆除/出让   0/4/5   other_manage_submit
    // ========== 获取权限数据(勿删) end ==========
    this.getData() // 获取数据
  },
  // ========== 生命周期: 页面初次渲染完成 ==========
  onReady: function () {},
  // ========== 生命周期: 页面显示 ==========
  onShow: function () {},
  // ========== 生命周期: 页面隐藏 ==========
  onHide: function () {},
  // ========== 判断权限 ==========
  judgeAuthEvent () {
    const Auth = this.data.Auth
    const manageType = this.data.listData.manageType
    let obj0 = {}
    let obj1 = {}
    manageType.forEach(b => {
      const submit = Auth[`${b.Auth}_submit`] // 提交
      const approve = Auth[`${b.Auth}_approve`] // 审批
      if (submit) obj0[b.id] = { submit }
      if (approve) obj1[b.id] = { approve }
    })
    const judgeAuth = {
      '0': obj0, 
      '1': obj1,
      '3': obj0
    }
    // console.log('judgeAuth', judgeAuth)
    this.setData({ judgeAuth })
  },
  // ========== 执行状态改变时 ==========
  approveChange () {
    this.setData({ dialogShow: null }) // 清除弹框显示
    this.getData() // 获取数据
  },
  // ========== 获取数据 ==========
  getData (RAndL) {
    const dataKey = 'data'
    if (!RAndL) {
      $app.$common.openLoading() // 开启加载
      this.setData({ ['param.pageNo']: 1 })
    }
    this.data.param.manageCompany = (this.data.userInfo.level === '4') ? this.data.userInfo.departid : null,
    this.data.param.launchDepart = (this.data.userInfo.level === '4') ? this.data.userInfo.departid : null
    $app.$api.agreePass.selectAssetsList({
      roleid: $app.userInfo.roleid,
      userid: $app.userInfo.id,
      ...this.data.param
    }).then(({ data, count }) => {
      console.log('api-列表数据', data, count)
      let newData = data || []
      for (const i in newData) { // 判断是否可编辑
        // (row.agreeType === '1' && (row.nextAgreePeople || '').includes(this.userInfo.id)) 审批
        const b = newData[i]
        let judgeEdit = false
        if (b.agreeType === '1') {
          const arr = b.nextAgreePeople ? b.nextAgreePeople.split(',') : []
          judgeEdit = arr.includes($app.userInfo.id + '')
        } else {
          judgeEdit = Boolean(b.launchUserId === $app.userInfo.id + '')
        }
        b.judgeEdit = judgeEdit
      }
      const total = count || 0
      if (RAndL === 'refresh') { // 刷新
        this.setData({ refreshing: false })
      } else if (RAndL === 'load') { // 加载
        newData = this.data[dataKey].concat(newData)
        this.setData({ loading: false })
      } else {
        this.setData({ backTop: !this.data.backTop })
      }
      this.setData({ [dataKey]: newData, total })
      $app.$common.closeLoading() // 关闭加载
    }).catch(({ type, res }) => {
      console.log('api-列表数据 catch', type, res)
      let newData = []
      let total = 0
      if (RAndL === 'refresh') { // 刷新
        this.setData({ refreshing: false })
      } else if (RAndL === 'load') { // 加载
        newData = this.data[dataKey]
        total = this.data.total
        const pageNo = this.data.param.pageNo - 1 // 页数
        this.setData({ loading: false, pageNo: pageNo })
      } else {
        this.setData({ backTop: !this.data.backTop })
      }
      this.setData({ [dataKey]: newData, total })
      $app.$common.closeLoading() // 关闭加载
      $app.$common.message('数据获取失败', 'error') // 提示信息
    })
  },
  // ========== 刷新 ==========
  refresh () {
    this.setData({ ['param.pageNo']: 1 })
    this.getData('refresh') // 获取数据
  },
  // ========== 加载 ==========
  load () {
    const dataKey = 'data'
    if (this.data[dataKey].length >= this.data.total) {
      this.setData({ loading: false })
      return
    }
    const pageNo = this.data.param.pageNo + 1
    this.setData({ ['param.pageNo']: pageNo })
    this.getData('load') // 获取数据
  },
  // ========== '详情按钮'点击事件 ==========
  detail (e) {
    const b = e.currentTarget.dataset.item
    const path = '/pages/home_workbench/work_approve_approve-detail/work_approve_approve-detail'
    wx.navigateTo({ url: `${path}?agreeNum=${b.agreeNum}` })
  },
  // ========== '更多按钮'点击事件 ==========
  more (e) {
    this.setData({ detailData: e.currentTarget.dataset.item }) // 详情数据
    const x = e.detail.x
    const y = e.detail.y
    // wx.nextTick(() => { this.selectComponent("#zjMore").open(x, y) })
    this.selectComponent("#zjMore").open(x, y)
  },
  // ========== 提交申请 ==========
  submit () {
    this.selectComponent("#zjMore").close() // 关闭'更多组件'
    $app.$common.confirm('submit', () => {
      $app.$common.openLoading() // 开启加载
      this.saveAgain({ // 继续保存
        api: 'agreeSubmit',
        param: { agreeNum: this.data.detailData.agreeNum },
        successText: '提交成功'
      })
    })
  },
  // ========== 审批 ==========
  approve () {
    this.selectComponent("#zjMore").close() // 关闭'更多组件'
    this.setData({
      ['detailData.agreeResult']: null,
      dialogShow: 'approve' // 打开弹窗
    })
  },
  approveSave (e) {
    // 1.验证必填项
    const param = this.data.detailData
    const verify = {
      agreeResult: '审批结果'
    }
    this.saveVerify(param, verify).then(() => {
      // 2. 继续保存
      $app.$common.openLoading() // 开启加载
      this.saveAgain({ // 继续保存
        api: 'agreePass',
        param: {
          agreeNumArray: [param.agreeNum],
          userid: $app.userInfo.id,
          agreeIdea: param.agreeIdea,
          agreeResult: param.agreeResult
        },
        successText: '审批成功'
      })
    })
  },
  // ========== 保存验证 ==========
  saveVerify (param, verify) {
    return new Promise((resolve) => {
      param = param || {}
      verify = verify || {}
      for (const k in verify) {
        const val = Array.isArray(param[k]) ? param[k][0] : param[k]
        if (!$app.$common.noNull(val)) {
          $app.$common.message(verify[k] + '不能为空') // 提示信息
          return
        }
      }
      resolve('complete')
    })
  },
  // ========== 继续保存 ==========
  saveAgain ({ api, param, successText }) {
    // 调用保存接口
    $app.$api.agreePass[api](param).then(({ data, message, code }) => {
      if (code === 2) {
        $app.$common.message(message)
        this.getData() // 获取数据
      } else {
        this.setData({ dialogShow: null }) // 关闭弹窗
        // $app.$common.closeLoading() // 关闭加载
        $app.$common.message(successText, 'success')
        $app.$common.message('保存成功', 'success')
        this.getData() // 获取数据
      }
    }).catch(() => {})
  }
})